<?php

namespace App\Modules;

use Illuminate\Http\Request;

use App\Modules\Interfaces\Module;

use Illuminate\Support\Arr;

use App\Models\Mysql\Orm\BaseOrm;
use Closure;
use App\Common\{
    Enum\Attributes,
    Helper,
    Http\Result,
    // Enum\Http,
    // Enum\ResultMsg
};
use App\Common\Http\Basics\Success;
use App\Common\Http\Interface\Index as Http;
use App\Common\Enum\TrueCode;

abstract class BaseModule implements Module
{
    /*请求数据*/
    public readonly array  $params;          //请求参数
    public readonly array  $loginInfo;  //请求的token信息
    public readonly string $method;         //请求方法

    // public readonly array $parameters;       //斜杠的路由参数

    public readonly array $file;       //文件
    /**/

    public function __construct(Request $request, Closure|null $formatFunc = null, array $funcParams = [], string|null $method = null)
    {

        $this->result = new Result([], Success::MODULE_NOT_DEFIND); //中间件那里设置的响应头信息


        $route = $request->route();


        $func = $method === null ? Arr::last(explode('@', $route[1]['uses'])) : $method;


        $this->params = $formatFunc === null  ?   $request->input() : $formatFunc($request->input());

        $this->loginInfo  = $request->get(Attributes::LOGIN_INFO->value, []);  //中间件那里解析到的获取登录信息


        $this->result->addHeader($request->get(Attributes::RES_HEADER->value, [])); //中间件那里设置的响应头信息



        // $this->parameters = $route->parameters();

        $this->file = $request->file();

        return $this->$func(...$funcParams);
    }

    /*返回数据*/
    public readonly Result $result;
    /**/


    /**
     * @description:   输出信息
     * @param {array} $data
     * @param {Http} $http
     * @param {array} $replace
     * @param {array} $header
     * @return {*}
     */
    public final function output(array $data,Http $http, array $replace = [], array $header = []): void
    {
        $this->result->addHeader($header);
        $this->result->setHttp($http, $replace);
        $this->result->setData($data);
    }

    /**
     * @description:   输出信息
     * @param {array} $data
     * @param {Http} $http
     * @param {array} $replace
     * @param {array} $header
     * @return {*}
     */
    public final function outputEnum(Http $http,array $replace = []): void
    {
        $this->result->setHttp($http, $replace);
    }




    /**
     * @description:  输出列表信息
     * @param {*} $list
     * @param {*} $total
     * @return {*}
     */
    public final function outputList($list, $total)
    {

        return  $this->output([
            'datalist' => $list,
            'pageNum'  => (int)$this->params['pageNum'],
            'pageSize'  => (int)$this->params['pageSize'],
            'total' => $total
        ], Success::SEL_SUCCESS);
    }


    public final function filtrate()
    {
        return empty($this->params) ? [] : array_filter($this->params, Helper::filtrfunction(...));
    }
}
